package com.ilink.groundservice.service.impl.Practice;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ilink.groundservice.entity.PO.Practice.AiXPracticeRecord;
import com.ilink.groundservice.entity.VO.AiX.AiXPracticeRecordResponse;
import com.ilink.groundservice.mapper.Practice.AiXPracticeRecordMapper;
import com.ilink.groundservice.mapper.Practice.AiXPracticeProjectMapper;
import com.ilink.groundservice.service.Practice.AiXPracticeRecordService;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPracticeRecordRequest;
import com.ilink.ilinkcommon.exception.BizIllegalException;
import com.ilink.ilinkcommon.utils.BeanUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class AiXPracticeRecordServiceImpl implements AiXPracticeRecordService {

    private final AiXPracticeRecordMapper practiceRecordMapper;
    private final AiXPracticeProjectMapper practiceProjectMapper;

    @Override
    @Transactional
    public Long startPracticeProject(Long projectId, String userId) {
        if (projectId == null) {
            throw new BizIllegalException("实践项目ID不能为空");
        }
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        // 检查项目是否存在
        if (practiceProjectMapper.selectById(projectId) == null) {
            throw new BizIllegalException("实践项目不存在");
        }
        
        // 检查是否已存在进行中的记录
        AiXPracticeRecordResponse existingRecord = practiceRecordMapper.selectPracticeRecordByUserAndProject(userId, projectId);
        if (existingRecord != null && "in_progress".equals(existingRecord.getStatus())) {
            throw new BizIllegalException("该实践项目已在进行中");
        }
        
        AiXPracticeRecord practiceRecord = new AiXPracticeRecord();
        practiceRecord.setUserId(userId);
        practiceRecord.setProjectId(projectId);
        practiceRecord.setStartTime(LocalDateTime.now());
        practiceRecord.setStatus("in_progress");
        practiceRecord.setCompletionRate(BigDecimal.ZERO);
        practiceRecord.setCreatedAt(LocalDateTime.now());
        practiceRecord.setUpdatedAt(LocalDateTime.now());
        
        int result = practiceRecordMapper.insert(practiceRecord);
        if (result <= 0) {
            throw new BizIllegalException("开始实践项目失败");
        }
        
        return practiceRecord.getRecordId();
    }

    @Override
    @Transactional
    public void submitPracticeWork(Long projectId, String userId, String notes) {
        if (projectId == null) {
            throw new BizIllegalException("实践项目ID不能为空");
        }
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        AiXPracticeRecordResponse existingRecord = practiceRecordMapper.selectPracticeRecordByUserAndProject(userId, projectId);
        if (existingRecord == null) {
            throw new BizIllegalException("实践记录不存在");
        }
        if (!"in_progress".equals(existingRecord.getStatus())) {
            throw new BizIllegalException("实践项目不在进行中状态");
        }
        
        AiXPracticeRecord practiceRecord = new AiXPracticeRecord();
        practiceRecord.setRecordId(existingRecord.getRecordId());
        practiceRecord.setStatus("submitted");
        practiceRecord.setCompletionRate(new BigDecimal("100.00"));
        practiceRecord.setNotes(notes);
        practiceRecord.setUpdatedAt(LocalDateTime.now());
        
        int result = practiceRecordMapper.updateById(practiceRecord);
        if (result <= 0) {
            throw new BizIllegalException("提交实践作业失败");
        }
    }

    @Override
    @Transactional
    public void endPracticeProject(Long projectId, String userId, Integer score) {
        if (projectId == null) {
            throw new BizIllegalException("实践项目ID不能为空");
        }
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        AiXPracticeRecordResponse existingRecord = practiceRecordMapper.selectPracticeRecordByUserAndProject(userId, projectId);
        if (existingRecord == null) {
            throw new BizIllegalException("实践记录不存在");
        }
        
        LocalDateTime endTime = LocalDateTime.now();
        Integer duration = null;
        if (existingRecord.getStartTime() != null) {
            duration = (int) ChronoUnit.MINUTES.between(existingRecord.getStartTime(), endTime);
        }
        
        AiXPracticeRecord practiceRecord = new AiXPracticeRecord();
        practiceRecord.setRecordId(existingRecord.getRecordId());
        practiceRecord.setEndTime(endTime);
        practiceRecord.setDuration(duration);
        practiceRecord.setStatus("completed");
        practiceRecord.setScore(score);
        practiceRecord.setUpdatedAt(LocalDateTime.now());
        
        int result = practiceRecordMapper.updateById(practiceRecord);
        if (result <= 0) {
            throw new BizIllegalException("结束实践项目失败");
        }
    }

    @Override
    @Transactional
    public void updatePracticeRecord(AiXPracticeRecordRequest request, String userId) {
        if (request == null || request.getProjectId() == null) {
            throw new BizIllegalException("请求参数不能为空");
        }
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        AiXPracticeRecordResponse existingRecord = practiceRecordMapper.selectPracticeRecordByUserAndProject(userId, request.getProjectId());
        if (existingRecord == null) {
            throw new BizIllegalException("实践记录不存在");
        }
        
        AiXPracticeRecord practiceRecord = BeanUtils.copyBean(request, AiXPracticeRecord.class);
        practiceRecord.setRecordId(existingRecord.getRecordId());
        practiceRecord.setUserId(userId);
        practiceRecord.setUpdatedAt(LocalDateTime.now());
        
        int result = practiceRecordMapper.updateById(practiceRecord);
        if (result <= 0) {
            throw new BizIllegalException("更新实践记录失败");
        }
    }

    @Override
    public IPage<AiXPracticeRecordResponse> getUserPracticeRecords(String userId, String status, Integer page, Integer size) {
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        Page<AiXPracticeRecordResponse> pageQuery = new Page<>(page, size);
        return practiceRecordMapper.selectPracticeRecordPage(pageQuery, userId, status);
    }

    @Override
    public AiXPracticeRecordResponse getPracticeRecordByUserAndProject(String userId, Long projectId) {
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        if (projectId == null) {
            throw new BizIllegalException("实践项目ID不能为空");
        }
        
        return practiceRecordMapper.selectPracticeRecordByUserAndProject(userId, projectId);
    }

    @Override
    public Map<String, Object> getUserPracticeStatistics(String userId) {
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        return practiceRecordMapper.selectPracticeStatistics(userId);
    }

    @Override
    public List<AiXPracticeRecordResponse> getCompletedPracticeRecords(String userId) {
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        return practiceRecordMapper.selectCompletedPracticeRecords(userId);
    }

    @Override
    public List<AiXPracticeRecordResponse> getInProgressPracticeRecords(String userId) {
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        return practiceRecordMapper.selectInProgressPracticeRecords(userId);
    }
} 